const ObjectID = require('mongodb').ObjectID;
const async = require('async');
const orderCode = require('yi-order-number');

module.exports = {
    open: false,
    description: '直接购买商品结算价格',
    handler(req, res, next) {
        const doc = req.body;
        req.mongo.collection('goods').findOne({_id: doc.goodsId,storeId:doc.storeId}, (e0, goods) => {
            if (e0 || !goods) {
                return res.reply({code: 10001, message: '商品信息异常请重试'});
            } else {
                let authInfo = req.context || req.context.authInfo;
                if (!req.context || !req.context.authInfo) {
                    return res.err.unauthorized();
                }
                authInfo = authInfo.authInfo;
                let id = ObjectID(authInfo._id);

                let orderId = new ObjectID();
                let orderNo = orderCode.getOrderNo();

//                let orderItemIds = [];

                let order = {
                    _id:orderId,
                    mallId: goods.mallId,
                    storeId: goods.storeId,
                    userId: id,
                    orderNo: orderNo,
                    orderType:goods.type,
                    orderStatus: "待付款",
                    address:doc.address,
                    userRemark:doc.userRemark
                };
                let orderItem = {
                    _id:new ObjectID(),
                    orderNo: orderNo,
                    orderType: goods.type,
                    goodsId: goods._id,
                    name: goods.name,
                    model: goods.model,
                    modelEx: goods.modelEx,
                    goodsCode: goods.goodsCode,
                    color: goods.color,
                    measure: goods.measure,
                    salePrice: goods.salePrice,
                    actualPrice: goods.actualPrice,
                    label: goods.label,
                    image: goods.image,
                    quantity: doc.buyCount
                };
//                orderItemIds.push(orderItem._id);
//                order.orderItemIds = orderItemIds;

                let pay = goods.actualPrice * doc.buyCount; //商品金额

                order.orderAmount = pay;

                if(doc.couponId){
                    req.mongo.collection('coupon').findOne({_id:doc.couponId,userId:id},(e2,r2)=>{
                        if (e2 || !r2) return res.reply({code:20001,message:'优惠券信息异常请重试',data:pay});
                        let faceValue = 0;

                        r2.storeIds.forEach((storeId)=>{
                            if(storeId.toString()===doc.storeId.toString()){
                                if(pay >= r2.minPrice){
                                    faceValue = r2.facevalue;
                                }
                            }
                        });

                        if(faceValue>0){
                            pay = (pay-faceValue) > 0 ? pay-faceValue : 0;         //减去优惠券面值后支付金额

                            order.couponId = doc.couponId;
                            order.facevalue = faceValue;
                            order.orderPayAmount = pay;
                        }else{
                            order.orderPayAmount = pay;
                        }

                        async.auto([
                                callback => req.mongo.collection('order').insertOne(order,callback),
                                callback => req.mongo.collection('orderItem').insertOne(orderItem,callback),
                            ],
                            (error, result) => {
                                if(error) return res.err.mongoError(error);
                                req.mongo.collection('order').aggregate([
                                    {$match: {_id: orderId}},
                                    {
                                        $lookup: {
                                            from: "coupon",
                                            localField: "couponId",
                                            foreignField: "_id",
                                            as: "coupon"
                                        }
                                    },
                                    {
                                        $lookup: {
                                            from: "orderItem",
                                            localField: "orderNo",
                                            foreignField: "orderNo",
                                            as: "orderItems"
                                        }
                                    }
                                ]).toArray((e4, r4) => {
                                    if (e4) return res.err.mongoError(e4);
                                    return res.reply({code: 0, message: '购物车结算', data: r4});
                                });
                            });
                    });
                }else{

                    order.orderPayAmount = pay;

                    async.auto([
                            callback => req.mongo.collection('order').insertOne(order,callback),
                            callback => req.mongo.collection('orderItem').insertOne(orderItem,callback),
                        ],
                        (error, result) => {
                            if(error) return res.err.mongoError(error);
                            req.mongo.collection('order').aggregate([
                                {$match: {_id: orderId}},
                                {
                                    $lookup: {
                                        from: "orderItem",
                                        localField: "orderNo",
                                        foreignField: "orderNo",
                                        as: "orderItems"
                                    }
                                }
                            ]).toArray((e4, r4) => {
                                if (e4) return res.err.mongoError(e4);
                                return res.reply({code: 0, message: '购物车结算', data: r4});
                            });
                        });
                }


            }
        });
    }
};